package com.cade.agriculturemall.view.personalCenter.ordersManage.OrderItems;


import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.SaveCallback;
import com.bumptech.glide.Glide;
import com.cade.agriculturemall.R;
import com.cade.agriculturemall.base.BaseAdapter;
import com.cade.agriculturemall.base.BaseViewHolder;
import com.cade.agriculturemall.model.AddressEntity;
import com.cade.agriculturemall.model.OrderEntity;
import com.cade.agriculturemall.model.ShoppingCarsEntity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;

/**
 * Created by Lobby on 2018/1/6.
 */

public class OrderAdapter extends BaseAdapter<BaseViewHolder> {
    private List<OrderViewModel> models = new ArrayList<>();
    private Context mContext;
    private TextView tvSingle;
    private ImageView img;
    private LinearLayout llOrder;

    public OrderAdapter(Context context) {
        this.mContext = context;
    }

    private OrderEntity orderEntity = new OrderEntity();

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public int getItemCount() {
        return models.size();
    }

    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        BaseViewHolder v = null;
        switch (viewType) {
            case OrderViewModel.TYPE_STATUS:
                v = new BaseViewHolder(parent, R.layout.item_order_status);
                break;
            case OrderViewModel.TYPE_ADRESS:
                v = new BaseViewHolder(parent, R.layout.item_settlement_address);
                break;
            case OrderViewModel.TYPE_REMARK:
                v = new BaseViewHolder(parent, R.layout.item_settlement_remark);
                break;
            case OrderViewModel.TYPE_SJ:
                v = new BaseViewHolder(parent, R.layout.item_settlement_shoper);
                break;
            case OrderViewModel.TYPE_CP:
                v = new BaseViewHolder(parent, R.layout.item_settlement_good);
                break;
            case OrderViewModel.TYPE_ITEMS:
                v = new BaseViewHolder(parent, R.layout.item_order_items);
                break;
            case OrderViewModel.TYPE_COUNT:
                v = new BaseViewHolder(parent, R.layout.item_order_price_count);
                break;
            case OrderViewModel.TYPE_SJ_FOOTER:
                v = new BaseViewHolder(parent, R.layout.item_order_footer);
                break;
        }
        return v;
    }

    @Override
    public int getItemViewType(int position) {
        return models.get(position).getType();
    }

    @Override
    public void onBindViewHolderWrapper(BaseViewHolder holder, int position) {
        int viewType = getItemViewType(position);
        switch (viewType) {
            case OrderViewModel.TYPE_STATUS:
                OrderEntity entity = (OrderEntity) models.get(position).getObject();
                renderStatus(holder, entity, "");
                break;
            case OrderViewModel.TYPE_ADRESS:
                AddressEntity addressEntity = (AddressEntity) models.get(position).getObject();
                TextView tvConteactorName = holder.findViewById(R.id.settlement_address_contractor);
                TextView tvPhone = holder.findViewById(R.id.settlement_address_phone);
                TextView tvAddress = holder.findViewById(R.id.settlement_address_tv_address);
                ImageView imageView = holder.findViewById(R.id.settlement_arrow_right);
                imageView.setVisibility(View.GONE);
                if (addressEntity != null) {
                    tvConteactorName.setText("收货人：" + addressEntity.getContractor());
                    tvPhone.setText( addressEntity.getMobile());
                    String address = "";
                    String procincecity = addressEntity.getProvince() + addressEntity.getCity();
                    if (addressEntity.getCounty() != null) {
                        address += procincecity + addressEntity.getCounty() + addressEntity.getStress() + addressEntity.getAddress();
                    } else {
                        address += procincecity + addressEntity.getStress() + addressEntity.getAddress();
                    }
                    tvAddress.setText("收货地址：" + address);
                }
                break;
            case OrderViewModel.TYPE_REMARK:
                String remark = (String) models.get(position).getObject();
                TextView remarkTv = holder.findViewById(R.id.item_remark_content_tv);
                remarkTv.setText(remark);
                break;
            case OrderViewModel.TYPE_SJ:
                String shopperName = (String) models.get(position).getObject();
                TextView tvShopperName = holder.findViewById(R.id.item_setttlement_address);
                tvShopperName.setText(shopperName);
                break;
            case OrderViewModel.TYPE_CP:
                ShoppingCarsEntity shoppingEntity = (ShoppingCarsEntity) models.get(position).getObject();
                ImageView imgShopper = holder.findViewById(R.id.item_setttlement_good_img);
                TextView tvGoodName = holder.findViewById(R.id.item_setttlement_good_tv_name);
                TextView tvGoodPrice = holder.findViewById(R.id.item_setttlement_good_tv_price);
                TextView tvGoodNumber = holder.findViewById(R.id.item_setttlement_good_tv_count);
                tvGoodName.setText(shoppingEntity.getProId().getTitle());
                tvGoodPrice.setText("￥" + shoppingEntity.getProId().getPriceNew());
                tvGoodNumber.setText("x" + shoppingEntity.getQuantitate());
                if (shoppingEntity.getProId().getPicture().size() != 0) {
                    Glide.with(mContext).load(shoppingEntity.getProId().getPicture().get(0)).into(imgShopper);
                }
                break;
            case OrderViewModel.TYPE_ITEMS:
                OrderEntity orderEntity = (OrderEntity) models.get(position).getObject();
                TextView tvOrderId, tvTime, tvPrice;
                String status = orderEntity.getOrderStatus();
                TableRow tableRowPayId = holder.findViewById(R.id.tablerow_pay_id);
                if (!status.equals("0000") & !status.equals("00000") & !status.equals("0001")) {
                    tableRowPayId.setVisibility(View.VISIBLE);
                }
                tvOrderId = holder.findViewById(R.id.item_order_items_tv_order_id);
                tvTime = holder.findViewById(R.id.item_order_items_tv_creat_time);
                ImageView imgPayWay = holder.findViewById(R.id.item_order_items_img_pay_way);
                tvPrice = holder.findViewById(R.id.item_order_items_tv_price);
                tvOrderId.setText(orderEntity.getOrderId());
                tvTime.setText(orderEntity.getOrderSetttlementTime());
                if (orderEntity.getPayWay().equals(1)) {
                    imgPayWay.setImageResource(R.mipmap.icon_alipay_72);
                } else if (orderEntity.getPayWay().equals(2)) {
                    imgPayWay.setImageResource(R.mipmap.icon_wechat_72);
                } else {
                    imgPayWay.setImageResource(R.mipmap.icon_bd_72);
                }
                tvPrice.setText("￥ " + Float.parseFloat(orderEntity.getOrderPriceCount()));
                break;
            case OrderViewModel.TYPE_COUNT:
                String countPrice = models.get(position).getObject().toString();
                TextView tvCountItems = holder.findViewById(R.id.item_order_price_tv_pay);
                tvCountItems.setText("￥" + countPrice);
                break;
//            case OrderViewModel.TYPE_SJ_FOOTER:
//                String totalCount = "kong";
//                if (!TextUtils.isEmpty(models.get(position).getObject().toString())) {
//                    totalCount = models.get(position).getObject().toString();
//                }
//                TextView tvTotalCont = holder.findViewById(R.id.item_order_price_tv_pay);
//                tvTotalCont.setText("￥ " + totalCount);
//                Button btnCancel = holder.findViewById(R.id.item_order_price_btn_cancel);
//                Button btnPay = holder.findViewById(R.id.item_order_price_btn_pay);
//                btnCancel.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//
//                    }
//                });
//                btnPay.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//
//                    }
//                });
//                RelativeLayout rl = holder.findViewById(R.id.item_order_price_ll);
//                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
//                        ViewGroup.LayoutParams.WRAP_CONTENT);
//                params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
//                rl.setLayoutParams(params);
//                break;
        }
    }

//    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(" dd HH:mm:ss");
//    前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
//    java.util.Date dt = new Date(showTime * 1000);
//    String sDateTime = simpleDateFormat.format(dt);  //得到精确到秒的表示：08/31/2006 21:08:00


    /**
     * @param holder
     * @param orderEntity
     * @param orderObjectId 等待支付倒计时结束时候，更换状态
     */
    public void renderStatus(BaseViewHolder holder, OrderEntity orderEntity, String orderObjectId) {
        String date = orderEntity.getOrderSetttlementTime();
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        Date dt2 = new Date();
        try {
            dt2 = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
//继续转换得到秒数的long型
        long orderTime = dt2.getTime() / 1000;

        String status = "";
        if (TextUtils.isEmpty(orderObjectId)) {
            status = orderEntity.getOrderStatus();
        } else {
            status = orderObjectId;
        }
        llOrder = holder.findViewById(R.id.item_order_status_ll);
        TextView tvTittle = holder.findViewById(R.id.item_order_status_tv_main);
        TextView tvSub = holder.findViewById(R.id.item_order_status_tv_sub);
        tvSingle = holder.findViewById(R.id.item_order_status_tv_single);
        img = holder.findViewById(R.id.item_order_status_image);
        switch (status) {
            case "0000":            //已下单未支付
                llOrder.setVisibility(View.VISIBLE);
                tvSingle.setVisibility(View.GONE);
                img.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.paying_icon_64));
                tvTittle.setText("等待买家付款");
                tvSub.setText("剩 " + mineTime + " 自动关闭");
                break;
            case "00000":           //已支付，等待派送
                tvSingle.setText("订单已取消");
                img.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.cancel_icon_64));
                break;
            case "0001":           //已支付，等待派送
                tvSingle.setText("等待卖家发货");
                img.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.sending_icon_64));
                break;
            case "0011":             //派送中，未收货
                llOrder.setVisibility(View.VISIBLE);
                tvSingle.setVisibility(View.GONE);
                long receiveTime = 24 * 7 * 60 * 60;
//                cutDown(holder, orderEntity, orderTime, receiveTime);
                img.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.sending_icon_64));
                tvTittle.setText("卖家已发货");
                tvTittle.setText("剩余 " + mineTime + " 自动确认");
                break;
            case "0111":           //已收货,未评价
                tvSingle.setText("已收货，等待卖家进行评价");
                img.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.receive_icon_64));
                break;
            case "1111":              //已收货,已评价
                tvSingle.setText("交易完成");
                img.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.receive_icon_64));
                break;
//            case "010001":        //等待派送，退货
//                tvSingle.setText("等待卖家退货");
//                break;
//            case "110001":        //已支付，未发货，未收货，退货
//                tvSingle.setText("卖家已发货，买家未收货，正在进行退货处理");
//                break;
//            case "010111":         //已收货，退货
//                tvSingle.setText("已收货，正在进行退货处理");
//                break;
//            case "110111":         //已收货，退款
//                tvSingle.setText("已收货，等待卖家进行退款");
//            break;
            default:
                img.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.default_error));
                tvSingle.setText("无效状态");
        }
        if (hide) {
            llOrder.setVisibility(View.GONE);
            tvSingle.setVisibility(View.VISIBLE);
            tvSingle.setText("订单已取消");
        } else {

        }
    }

    private boolean hide = false;

    String mineTime = "";

    public void cutDown(final BaseViewHolder holder, final OrderEntity orderEntity, long orderCreatTime, long time, float hour) {
//        long showTime = System.currentTimeMillis() / 1000;

        final long payTime = (long) (60 * 60 * hour);
        long timeNow = System.currentTimeMillis() / 1000;//秒
        long order = orderCreatTime;//秒
        if (timeNow - order <= payTime) {
            final int shengyushijian = (int) (payTime - (timeNow - order));
            Observable.interval(1, TimeUnit.SECONDS)
                    .take(shengyushijian)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<Long>() {
                        @Override
                        public void onCompleted() {
                            setEnd();
                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onNext(Long aLong) {
                            long showTime = shengyushijian - aLong - 1;//秒
                            if (aLong < payTime) {
                                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
//前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
                                java.util.Date dt = new Date(showTime * 1000);
                                mineTime = sdf.format(dt);  //得到精确到秒的表示：08/31/2006 21:08:00
                                notifyDataSetChanged();
                            } else if (aLong == payTime) {
// 修改订单状态
                                renderStatus(holder, orderEntity, "");
                                AVObject avObject = AVObject.createWithoutData("order", orderEntity.getObjectId());
                                avObject.put("order_status", mContext.getResources().getString(R.string.order_cancel));
                                avObject.saveInBackground(new SaveCallback() {
                                    @Override
                                    public void done(AVException e) {
                                        if (e == null) {
                                            Toast.makeText(mContext, "状态修改", Toast.LENGTH_SHORT).show();
                                        } else {
                                            e.printStackTrace();
                                        }
                                    }
                                });
//                                释放优惠券
                                releaseTicket(orderEntity.getTicketId());
                            }
                        }
                    });
        }

    }

    public void releaseTicket(String ticketId) {
        AVObject avObject = AVObject.createWithoutData("ticket_discount", ticketId);
        avObject.put("had_use", "0");
        avObject.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e != null) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void setEnd() {
// 修改订单状态
        if (orderEntity.getObjectId() != null) {
            hide = true;
            AVObject avObject = AVObject.createWithoutData("order", orderEntity.getObjectId());
            avObject.put("order_status", mContext.getResources().getString(R.string.order_cancel));
            avObject.saveInBackground(new SaveCallback() {
                @Override
                public void done(AVException e) {
                    if (e == null) {
                        Toast.makeText(mContext, "状态修改", Toast.LENGTH_SHORT).show();
                        notifyDataSetChanged();
                    } else {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    public void setModels(List<OrderViewModel> models) {
        this.models = models;
        if (models.size() != 0) {
            OrderEntity entityModel = (OrderEntity) models.get(0).getObject();
            orderEntity = entityModel;
            String date = entityModel.getOrderSetttlementTime();
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
            Date dt2 = new Date();
            try {
                dt2 = sdf.parse(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
//继续转换得到秒数的long型
            long orderTime = dt2.getTime() / 1000;
            entityModel.getOrderStatus();

// cutDown(null, entityModel, orderTime, 0, 0.5f);//          30分钟
            if (entityModel.getOrderStatus().equals(mContext.getResources().getString(R.string.order_status_no_pay))) {
                cutDown(null, entityModel, orderTime, 0, 0.5f);
            }
//        if(entityModel.getOrderStatus()=="0000") {
//            cutDown(null, entityModel, orderTime, 0, 0.5f);
//        }else if(entityModel.getOrderStatus()=="0011"){
//            cutDown(null, entityModel, orderTime, 0, 240f);
//        }
        }
    }
}
